// utils/paymentUtils.js
import { Platform } from "react-native"
import Alipay from "@uiw/react-native-alipay"
import * as Burnt from "burnt"
import { finishTransaction, getAvailablePurchases, getReceiptIOS } from "react-native-iap"

import { translate } from "@/i18n"
import { _rootStore } from "@/models"
import {
  checkOrder,
  createOrder,
  getCDKS,
  verifyIAPAppStoreTransaction,
  createAliPayment,
} from "@/services/api/order"

/**
 * 统一支付处理函数：处理邀请码逻辑、Android支付宝支付、以及iOS内购流程。
 * @param {object} options
 * @param {boolean} options.showCode - 是否显示邀请码页
 * @param {string} options.activeCode - 邀请码内容
 * @param {string} options.selectedProductId - 当前选中的商品ID
 * @param {Array} options.productList - 商品列表
 * @param {object} options.userStore - 用户store对象
 * @param {object} options.router - 路由对象
 * @param {Function} options.paySuccess - 支付成功时的回调
 * @param {Function} options.onClose - 关闭当前页面的回调
 * @param {object} options.loadingModalRef - LoadingModal 的 ref（注意：current 调用时需要加 ?.current）
 * @param {Array} options.subscriptions - 当前内购订阅列表（iOS 使用）
 */

interface Props {
  selectedProduct: any
  userStore: any
  systemStore: any
  router: any
  paySuccess: (obj?: any) => void
  onClose: () => void
  subscriptions: Array<any>
  products: Array<any>
  fetchProducts: (params: { skus: string[]; type: "subs" | "in-app" }) => Promise<void>
  requestPurchase?: any
}

// --------------
// 轮询函数：返回一个 Promise，直到订单状态为 "done" 且拿到 CDK 列表
// --------------
function startPollingAuth(orderNum: string, checkItem: { quantity?: number }): Promise<string[]> {
  return new Promise((resolve, reject) => {
    let attempts = 0
    const maxAttempts = 3

    const intervalId = setInterval(async () => {
      attempts++
      try {
        const res: any = await checkOrder({ orderNum })
        const state = res.data.data.order.state
        if (state === "done") {
          // 成功获取到状态为 done，拿 CDK
          const size = checkItem.quantity && checkItem.quantity > 0 ? checkItem.quantity : 1
          const cdksRes: any = await getCDKS({ size })
          const cdkList: string[] = cdksRes.data.data.cdks.map(
            (item: { cdkId: string }) => item.cdkId,
          )
          clearInterval(intervalId)
          resolve(cdkList)
          return
        }

        if (attempts >= maxAttempts) {
          clearInterval(intervalId)
          reject(
            new Error(`startPollingAuth: 已尝试 ${maxAttempts} 次，仍未拿到 "done"，停止轮询。`),
          )
        }
      } catch (err) {
        clearInterval(intervalId)
        reject(err)
      }
    }, 3000)
  })
}

// Android支付宝支付处理函数
async function handleAndroidAlipay(
  orderNum: string,
  systemStore: any,
  paySuccess: (obj?: any) => void,
  onClose: () => void,
) {
  try {
    console.log("创建支付宝支付订单...")
    const aliPaymentRes: any = await createAliPayment({ orderNum })
    console.log("支付宝支付订单创建成功:", aliPaymentRes.data)

    const orderStr = aliPaymentRes.data?.data?.orderStr
    if (!orderStr) {
      throw new Error("支付宝订单字符串为空")
    }

    // 启动订单状态轮询
    let count = 0
    const maxCount = 30
    const intervalId = setInterval(() => {
      count++
      if (count > maxCount) {
        clearInterval(intervalId)
        console.log("订单状态轮询超时")
        return
      }

      checkOrder({ orderNum })
        .then((res: any) => {
          console.log("检查订单状态:", res.data)
          if (res.data?.data?.order?.state === "done") {
            clearInterval(intervalId)
            console.log("支付成功！")
            systemStore.hideModal()
            paySuccess()
            setTimeout(() => {
              onClose()
            }, 500)
          }
        })
        .catch((err) => {
          console.error("检查订单状态失败:", err)
        })
    }, 1000)

    // 调用支付宝支付
    console.log("调用支付宝支付...")
    const timeout = (ms: number) =>
      new Promise((resolve, reject) => setTimeout(() => reject(new Error("支付超时")), ms))

    const alipayResult: any = await Promise.race([
      Alipay.alipay(orderStr),
      timeout(15000), // 15秒超时
    ])

    console.log("支付宝支付结果:", alipayResult)

    if (alipayResult.resultStatus === "9000") {
      console.log("支付成功")
      // 支付成功，等待轮询确认
    } else if (alipayResult.resultStatus === "6001") {
      console.log("用户取消支付")
      clearInterval(intervalId)
      systemStore.hideModal()
      Burnt.toast({
        title: translate("pay:paymentCancelled"),
        from: "top",
        preset: "error",
        duration: 1.5,
      })
    } else {
      console.error("支付失败:", alipayResult)
      clearInterval(intervalId)
      systemStore.hideModal()
      Burnt.toast({
        title: "支付失败",
        from: "top",
        preset: "error",
        duration: 1.5,
      })
    }
  } catch (error: any) {
    console.error("Android支付宝支付失败:", error)
    systemStore.hideModal()
    Burnt.toast({
      title: error.message || "支付失败",
      from: "top",
      preset: "error",
      duration: 1.5,
    })
  }
}

// —— 主逻辑：先创建订单，再调用支付，最后轮询获取 CDK ——
export async function handlePayment(options: Props) {
  const { selectedProduct, systemStore, paySuccess, onClose, products, fetchProducts } = options

  if (!selectedProduct) {
    return
  }

  // 检查是否是赠送(gift)订单
  const isGiftOrder = selectedProduct?.gift === true
  // 用户填写的赠送数量
  const giftQuantity = selectedProduct?.quantity || 1

  let orderNum: string = ""
  try {
    systemStore.showModal({
      message: translate("pay:creatingOrder"),
      maxDuration: 30000,
    })
    const orderRes: any = await createOrder({ productId: selectedProduct.id })
    orderNum = orderRes?.data?.data?.orderNum
    if (!orderNum) {
      throw new Error(translate("pay:orderCreationFailed"))
    }
  } catch (err: any) {
    systemStore.hideModal()
    console.error("创建订单失败：", err)
    Burnt.toast({
      title: translate("pay:orderCreationFailed"),
      from: "top",
      preset: "error",
      duration: 1.5,
    })
    return
  }

  try {
    console.log("=== 支付调试信息 ===")
    console.log("Platform:", Platform.OS)
    console.log("selectedProduct:", selectedProduct)
    console.log("orderNum:", orderNum)

    if (Platform.OS === "android") {
      // Android使用支付宝支付
      console.log("=== Android支付宝支付 ===")
      await handleAndroidAlipay(orderNum, systemStore, paySuccess, onClose)
      return
    } else {
      // iOS使用IAP支付 —— 只触发购买，后续完全交给 purchaseUpdatedListener/onPurchaseSuccess 处理
      console.log("=== iOS IAP支付 ===")
      console.log("products:", products)

      if (!products || products.length === 0) {
        console.log("没有IAP产品，正在获取...")
        const skus = ["octopus_base_package_1"]
        await fetchProducts({ skus, type: "in-app" })
        console.log("IAP产品获取完成")
      }

      const sku = selectedProduct.appleSubscribeSku || selectedProduct.appleSku
      console.log("准备购买SKU:", sku)

      options.requestPurchase({
        request: {
          ios: {
            sku,
            appAccountToken: orderNum, // 用于你服务端核验时关联订单
          },
          android: {
            skus: [sku],
            obfuscatedAccountIdAndroid: orderNum,
          },
        },
      })

      // 关键：iOS 下不要在这里直接调用 paySuccess/onClose，等待 onPurchaseSuccess 完成核验 + finishTransaction 后再处理
      return
    }

    // 支付成功后（仅 Android 路径）：如果是赠送订单，走轮询；否则直接 paySuccess + 关闭
    if (Platform.OS === "android") {
      if (isGiftOrder) {
        try {
          const cdkList = await startPollingAuth(orderNum, { quantity: giftQuantity })
          const cdkText = cdkList.join("\n")
          paySuccess({ isGiftOrder, cdkText })
        } catch (pollErr) {
          console.warn("startPollingAuth 异常：", pollErr)
          Burnt.toast({
            title: translate("pay:getCdkFailed"),
            from: "top",
            preset: "error",
            duration: 2,
          })
        }
        return
      } else {
        paySuccess()
        setTimeout(() => {
          onClose()
        }, 500)
        return
      }
    }
  } catch (err: any) {
    systemStore.hideModal()
    if (err.code !== "E_USER_CANCELLED") {
      console.warn("IAP 支付异常：", err)
    }
    Burnt.toast({
      title: translate("pay:paymentCancelled", { reason: err }),
      from: "top",
      preset: "error",
      duration: 1,
    })
    return
  }
}

export const restorePurchase = async (availablePurchases: any) => {
  const { systemStore } = _rootStore
  try {
    systemStore.showModal({
      message: translate("pay:restorePurchases"),
      maxDuration: 10000,
    })
    await getAvailablePurchases()
    const purchases = availablePurchases
    systemStore.hideModal()
    if (purchases && purchases.length > 0) {
      Burnt.toast({
        title: `检测到 ${purchases.length} 条购买记录，系统将在24小时内恢复购买`,
        from: "top",
        duration: 1,
      })
    } else {
      Burnt.toast({
        title: "没有找到可恢复的购买记录！",
        from: "top",
        preset: "error",
        duration: 1,
      })
    }
  } catch (err) {
    console.error("恢复购买失败:", err)
    Burnt.toast({
      title: "恢复购买失败，请稍后重试！",
      preset: "error",
      from: "top",
      duration: 1,
    })
  }
}

export function splitByIntl(priceString: string, currencyCode: string, localizedPrice?: string) {
  try {
    const value = Number(priceString)
    // 不传 locale 参数，自动取运行环境的默认 locale
    const formatter = new Intl.NumberFormat(undefined, {
      style: "currency",
      currency: currencyCode,
    })
    const parts = formatter.formatToParts(value)

    const symbol = parts.find((p) => p.type === "currency")?.value ?? ""
    // 把 integer/decimal/fraction/group 三种类型拼成数字部分
    const amount = parts
      .filter((p) => ["integer", "group", "decimal", "fraction"].includes(p.type))
      .map((p) => p.value)
      .join("")
    return { symbol, amount }
  } catch {
    //处理错误，人工处理
    //localizedPrice  从localizedPrice中分离货币符号
    if (localizedPrice) {
      const symbol = localizedPrice.match(/[\D.,]+/g)?.[0]
      const amount = localizedPrice.replace(/[\D]+/g, "")
      return { symbol, amount }
    }
    return {
      symbol: "",
      amount: priceString,
    }
  }
}
